<template>
  <div class="dialog-wrapper" v-if="visible" @click.self="closeDialog">
    <div class="dialog-container">
      <div class="dialog-header">
        <h3>{{ title }}</h3>
        <button class="close-btn" @click="closeDialog">&times;</button>
      </div>
      <div class="dialog-body">
        <div class="loading" v-if="loading">
          数据加载中...
        </div>
        <div v-else-if="error" class="error">
          {{ error }}
        </div>
        <div v-else class="data-content">
          <!-- 如果是对象或数组，使用美化展示 -->
          <div v-if="isObject(data) || isArray(data)">
            <!-- 表格形式展示数组数据 -->
            <div v-if="isArray(data) && data.length > 0 && isObject(data[0])">
              <table class="data-table">
                <thead>
                  <tr>
                    <th v-for="(value, key) in data[0]" :key="key">{{ getLabel(key) }}</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(item, index) in data" :key="index">
                    <td v-for="(value, key) in item" :key="key">
                      <span v-if="isDateField(key)">{{ formatDate(value) }}</span>
                      <span v-else>{{ value }}</span>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            
            <!-- 表单形式展示对象数据 -->
            <div v-else-if="isObject(data)">
              <div class="data-form">
                <div 
                  v-for="(value, key) in data" 
                  :key="key" 
                  class="form-item"
                  :class="{ 'form-item-row': isComplexObject(value) }"
                >
                  <label class="form-label">{{ getLabel(key) }}:</label>
                  
                  <!-- 复杂对象，递归展示 -->
                  <div v-if="isComplexObject(value)" class="form-value complex-value">
                    <div v-if="isArray(value) && value.length > 0 && isObject(value[0])">
                      <table class="nested-table">
                        <thead>
                          <tr>
                            <th v-for="(v, k) in value[0]" :key="k">{{ getLabel(k) }}</th>
                          </tr>
                        </thead>
                        <tbody>
                          <tr v-for="(item, idx) in value" :key="idx">
                            <td v-for="(v, k) in item" :key="k">
                              <span v-if="isDateField(k)">{{ formatDate(v) }}</span>
                              <span v-else>{{ v }}</span>
                            </td>
                          </tr>
                        </tbody>
                      </table>
                    </div>
                    <div v-else class="nested-object">
                      <pre>{{ formatJson(value) }}</pre>
                    </div>
                  </div>
                  
                  <!-- 简单值 -->
                  <div v-else class="form-value">
                    <span v-if="isDateField(key)">{{ formatDate(value) }}</span>
                    <span v-else-if="isUrlField(key)"><a :href="value" target="_blank">{{ value }}</a></span>
                    <span v-else>{{ value }}</span>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 其他情况，使用JSON格式展示 -->
            <div v-else>
              <pre>{{ formatJson(data) }}</pre>
            </div>
          </div>
          
          <!-- 简单值直接展示 -->
          <div v-else>
            {{ data }}
          </div>
        </div>
      </div>
      <div class="dialog-footer">
        <button @click="closeDialog">关闭</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ApiDataDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '接口数据'
    },
    apiUrl: {
      type: String,
      default: ''
    },
    apiParams: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['update:visible'],
  data() {
    return {
      loading: false,
      data: null,
      error: null
    };
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.fetchData();
      }
    }
  },
  methods: {
    closeDialog() {
      this.$emit('update:visible', false);
    },
    async fetchData() {
      if (!this.apiUrl) {
        this.error = '未提供API地址';
        return;
      }

      this.loading = true;
      this.error = null;
      
      try {
        const response = await fetch(this.apiUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(this.apiParams)
        });
        
        if (!response.ok) {
          throw new Error(`HTTP error! Status: ${response.status}`);
        }
        
        const result = await response.json();
        this.data = result;
      } catch (err) {
        this.error = `请求失败: ${err.message}`;
        console.error('API请求错误:', err);
      } finally {
        this.loading = false;
      }
    },
    isObject(obj) {
      return obj !== null && typeof obj === 'object' && !Array.isArray(obj);
    },
    isArray(obj) {
      return Array.isArray(obj);
    },
    isComplexObject(obj) {
      return this.isObject(obj) || (this.isArray(obj) && obj.length > 0 && this.isObject(obj[0]));
    },
    formatJson(json) {
      return JSON.stringify(json, null, 2);
    },
    // 字段中文标签映射
    getLabel(key) {
      const labelMap = {
        // 通用字段
        'id': 'ID',
        'name': '名称',
        'code': '编码',
        'type': '类型',
        'status': '状态',
        'date': '日期',
        'time': '时间',
        'createTime': '创建时间',
        'updateTime': '更新时间',
        'remark': '备注',
        
        // 企业相关字段
        'companyName': '企业名称',
        'creditCode': '统一社会信用代码',
        'legalRepresentative': '法定代表人',
        'registeredCapital': '注册资本',
        'paidInCapital': '实缴资本',
        'establishmentDate': '成立日期',
        'businessTermStartDate': '营业期限开始',
        'businessTermEndDate': '营业期限结束',
        'companyType': '企业类型',
        'registrationAuthority': '登记机关',
        'registeredAddress': '注册地址',
        'businessScope': '经营范围',
        'registrationStatus': '登记状态',
        
        // 股东相关字段
        'shareholders': '股东信息',
        'shareholderName': '股东名称',
        'holdingRatio': '持股比例',
        'subscribedCapital': '认缴出资额',
        'paidInCapital': '实缴出资额',
        'investmentMethod': '出资方式',
        
        // 人员相关字段
        'keyPersonnel': '主要人员',
        'position': '职位',
        'employmentDate': '任职日期',
        
        // 风险相关字段
        'riskLevel': '风险等级',
        'riskType': '风险类型',
        'riskDescription': '风险描述',
        'score': '评分',
        'level': '等级',
        
        // 财务相关字段
        'revenue': '营业收入',
        'profit': '利润',
        'assets': '资产',
        'liabilities': '负债',
        'equity': '权益',
        
        // 司法相关字段
        'litigationCount': '涉诉次数',
        'dishonestyRecord': '失信记录',
        'executedPerson': '被执行人',
        'administrativePenalty': '行政处罚',
        
        // 默认使用字段名
        [key]: key
      };
      
      // 如果是驼峰命名，转换为带空格的形式
      if (!labelMap[key]) {
        return key.replace(/([A-Z])/g, ' $1').trim();
      }
      
      return labelMap[key] || key;
    },
    // 判断是否为日期字段
    isDateField(key) {
      const dateKeywords = ['date', 'time', 'Date', 'Time', '期限', '日期', '时间'];
      return dateKeywords.some(keyword => key.includes(keyword));
    },
    // 判断是否为URL字段
    isUrlField(key) {
      const urlKeywords = ['url', 'link', '网址', '链接'];
      return urlKeywords.some(keyword => key.includes(keyword));
    },
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '--';
      try {
        const date = new Date(dateString);
        if (isNaN(date.getTime())) return dateString;
        return date.toLocaleDateString('zh-CN');
      } catch (e) {
        return dateString;
      }
    }
  }
};
</script>

<style scoped>
.dialog-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-container {
  background: white;
  border-radius: 8px;
  width: 80%;
  max-width: 800px;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.dialog-header {
  padding: 16px 24px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.close-btn:hover {
  color: #333;
}

.dialog-body {
  padding: 20px 24px;
  flex: 1;
  overflow-y: auto;
  min-height: 200px;
}

.loading, .error {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  font-size: 16px;
}

.error {
  color: #ff4d4f;
}

.data-content pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.5;
}

.dialog-footer {
  padding: 16px 24px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer button {
  padding: 8px 16px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.dialog-footer button:hover {
  background-color: #096dd9;
}

/* 表格样式 */
.data-table, .nested-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

.data-table th, .nested-table th {
  background-color: #f5f7fa;
  padding: 12px 8px;
  text-align: left;
  font-weight: 500;
  border-bottom: 1px solid #e8e8e8;
}

.data-table td, .nested-table td {
  padding: 10px 8px;
  border-bottom: 1px solid #e8e8e8;
}

.data-table tr:hover, .nested-table tr:hover {
  background-color: #f5f7fa;
}

/* 表单样式 */
.data-form {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.form-item {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.form-item:last-child {
  border-bottom: none;
}

.form-item-row {
  flex-direction: column;
  align-items: flex-start;
}

.form-label {
  font-weight: 500;
  color: #555;
  min-width: 120px;
  flex-shrink: 0;
}

.form-value {
  flex: 1;
  color: #333;
  word-break: break-word;
}

.form-value a {
  color: #1890ff;
  text-decoration: none;
}

.form-value a:hover {
  text-decoration: underline;
}

.complex-value {
  width: 100%;
  margin-top: 8px;
}

.nested-object pre {
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
  font-size: 13px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dialog-container {
    width: 95%;
    max-height: 90vh;
  }
  
  .form-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .form-label {
    min-width: auto;
    margin-bottom: 4px;
  }
}
</style>